/**
	Generic Widget Lockscreen SDK
    Copyright (C) 2011 Jorge Garrido Oval, nickname: FireZenk

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/

package org.firezenk.gwl.addon;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.ActivityManager.RunningServiceInfo;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class UnlockButton extends AppWidgetProvider {

	public static String ACTION_WIDGET_FORCE_UPDATE = 
		"org.firezenk.gwl.addon.ACTION_WIDGET_FORCE_UPDATE";
	
	private int[] appWidgetIds;
	private AppWidgetManager appWidgetManager;
	private RemoteViews views;
	private Context context;

	@Override
	public void onEnabled(final Context context) {
		super.onEnabled(context);
		this.context=context;
		
		//Apply pending intent to do forced updates
		doUpdate(loadElements(context));
	}
	
	/**
	 * Load widget elements
	 * @param context
	 * @return
	 */
	private int loadElements(Context context) {
		appWidgetManager = AppWidgetManager.getInstance(context);
		ComponentName thisWidget = new ComponentName(context, UnlockButton.class);
		appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
		return appWidgetIds.length;
	}

	/**
	 * This function process all broadcast received and do the proper action
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		if (intent.getAction().equals(ACTION_WIDGET_FORCE_UPDATE)) {
			this.context=context;
			if (isMyServiceRunning(context)) {
				
				//	If the GWL service is running send a question 
				//	to see if the program is on the screen
				Log.d("LOCK_WIDGET", "Sending shown question...");
				Intent i = new Intent("com.firezenk.gwlads.is_shown");
				context.sendStickyBroadcast(i);
				
			} else {
				
				//	If the GWL service is not running: prepare and start the service
				//	using Component name to start the external service
				Log.d("LOCK_WIDGET", "Starting lockscreen service & invoke...");
				Intent i = new Intent();
		        String pack="com.firezenk.gwlads";
		        String clas="com.firezenk.simplylock.core.CoreService";
		        i.setComponent(new ComponentName(pack,clas));
		        i.putExtra("FROM_WIDGET", true);
				context.startService(i);
				
			}
		} else if(intent.getAction().equals("com.firezenk.gwlads.shown_response")) {
			if (intent.getBooleanExtra("IS_SHOWN", false)) {
				
				//	If receive the answer of the "shown question" is yes
				//	means that GWL is on screen and want to unlock the screen
				Log.d("LOCK_WIDGET", "Sending kill signal...");
				Intent i = new Intent("com.firezenk.gwlads.kill");
				context.sendBroadcast(i);
				
			} else {
				
				//	If receive the answer of the "shown question" is yes
				//	means that GWL is not on screen and want to lock the screen
				Log.d("LOCK_WIDGET", "Sending invoke signal...");
				Intent i = new Intent("com.firezenk.gwlads.invoke");
				context.sendBroadcast(i);
				
			}
		}
	}

	/**
	 * Receive Android update order
	 */
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		this.context=context;
		final int N = appWidgetIds.length;
		this.appWidgetIds = appWidgetIds;
		this.appWidgetManager = appWidgetManager;
		doUpdate(N);
	}	

	/**
	 * Do the widget update
	 * @param N
	 */
	private void doUpdate(int N) {
		for (int i = 0; i < N; i++) {
			Log.d("LOCK_WIDGET", "Updating widget...");
			
			int appWidgetId = appWidgetIds[i];
			views = new RemoteViews(context.getPackageName(), R.layout.widget_lock);
			
			//Prepare broadcast action to forced update
			Intent update = new Intent(context, UnlockButton.class);
			update.setAction(ACTION_WIDGET_FORCE_UPDATE);
			PendingIntent update2= PendingIntent.getBroadcast(context, 0, update, 0);
			
			views.setOnClickPendingIntent(R.id.unlock, update2);
			
			appWidgetManager.updateAppWidget(appWidgetId, views);
		}
	}
	
	/**
	 * This function checks that the GWL service is running (Don't modify)
	 * @param context
	 * @return
	 */
	private boolean isMyServiceRunning(Context context) {
	    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if ("com.firezenk.simplylock.core.CoreService".equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}
}